import { existplayer,Read_player,Write_player,Add_player,__PATH,get_player_img,Write_json,Read_json
    ,alluser,Go,getPlayerAction,isNotNull } from "../game/sanguo.js";
import data from '../../model/sanguoData.js'
import fs from 'fs';
export class UserStart extends plugin {
    constructor() {
      super({
        /** 功能名称 */
        name: '三国|打工模块',
        /** 功能描述 */
        dsc: '打工模块',
        event: 'message',
        /** 优先级，数字越小等级越高 */
        priority: 600,
        rule: [
          {
            reg: /^(#|\/)开始打工$/,
            fnc: 'start',
          },
          {
            reg: /^(#|\/)结束打工$/,
            fnc: 'stop',
          },
        //   {
        //     reg: /^(#|\/)结束状态$/,
        //     fnc: 'stop2',
        //   },
          {
            reg: /^(#|\/)状态$/,
            fnc: 'tai',
          },
        ]
      });
    }
    async tai(e){
        let flag = await Go(e)
        if (!flag) {
          return false
       }
       e.reply(`空闲中`)
       return;
    }
    async stop2(e){
        const usr_qq = e.user_id; // 用户qq
        await redis.del(`sanguo:player:${usr_qq}:action`);
        await redis.del(`sanguo:${usr_qq}:action`);
    }
    async start(e){
        const usr_qq = e.user_id; // 用户qq

        if (!(await existplayer(1, usr_qq)) || !e.isGroup || !await Go(e)) {
        return false;
        }

        const now_time = new Date().getTime();

        const arr = {
        action: '打工', // 动作
        start_time: now_time,
        group_id: e.group_id || undefined,
        };

        await redis.set(`sanguo:player:${usr_qq}:action`, JSON.stringify(arr)); // redis设置动作
        e.reply('现在开始打工');
        return true;
    }
    async stop(e){
        if (!e.isGroup) return;

        const usr_qq = e.user_id;
        const ifExistPlay = await existplayer(1,usr_qq);
        if (!ifExistPlay) return;
        console.log(123);
        let action = await this.getPlayerAction(usr_qq);
        // let action = await redis.get(`sanguo:player:${usr_qq}:action`);
        console.log(action.action);
        if (!isNotNull(action) || action.action !== "打工") return;
        console.log(1);
        
        // 结算
        const now_time = new Date().getTime();
        const time = action.start_time !== null
          ? parseInt((now_time - action.start_time) / 1000 / 60)
          : parseInt((now_time - (action.end_time - action.time)) / 1000 / 60);
        
        const player = await Read_player(1, usr_qq);
        const size = time * 100;
        player.金钱 += size;
        await Write_player(1,usr_qq,player)
        const msg = [segment.at(usr_qq)];
        msg.push(`\n增加经济: ${size}`);
        e.reply(msg);
        
        // 关闭状态
        await redis.del(`sanguo:player:${usr_qq}:action`);
        return;        
    }
    async getPlayerAction(usr_qq) {
        let action = await redis.get(`sanguo:player:${usr_qq}:action`);
        action = JSON.parse(action); //转为json格式数据
        return action;
      }
}